
local Field = import("./Field.lua");
local Select = commonlib.inherit(Field);

Select:Property("Label");
Select:Property("Options");

local TriangleWidthUnitCount = 4;

function Select:Init(block, opt)
    Field._super.Init(self, block, opt);

    self:SetCanEdit(true);
    self:SetOptions(type(opt.options) == "table" and opt.options or {});   -- options = {{[1] = label, [2] = value}}
    local first_option = self:GetOptions()[1];
    self:SetValue(opt.value or (first_option and first_option[2] or ""));
    self:SetLabel(self:GetLabelByValue(self:GetValue()));

    return self;
end

function Select:GetLabelByValue(value)
    for _, option in ipairs(self:GetOptions()) do
        if (option[2] == value) then return option[1] end 
    end
    return value;
end

function Select:GetValueByLabel(label)
    for _, option in ipairs(self:GetOptions()) do
        if (option[1] == label) then return option[2] end
    end
    return label;
end

function Select:Render()
    local leftUnitCount, topUnitCount = self:GetLeftTopUnitCount();
    local widthUnitCount, heightUnitCount = self:GetWidthHeightUnitCount();
    self:SetBrushColor(0xffffffff);
    self:DrawInputValue(widthUnitCount, heightUnitCount, leftUnitCount, topUnitCount);
    -- if (self:IsEditing()) then return end 
    self:DrawText(self:GetText(), widthUnitCount - heightUnitCount - TriangleWidthUnitCount, heightUnitCount, leftUnitCount + heightUnitCount / 2, topUnitCount);

    local x, y = self:GetLeftTop();
    local w, h = self:GetWidthHeight();
    local padding = 9;
    local arrow_height = h - 2 * padding;
    local arrow_width = arrow_height * 2;
    local is_show_listbox = false;
    local blockly = self:GetBlockly();
    blockly:SetBrushColor(0xccccccff);
    blockly:DrawTriangle(x + w - arrow_width - padding, y + padding,  x + w - padding, y + padding, x + w - padding - arrow_width / 2, y + padding + arrow_height );
end

function Select:UpdateWidthHeightUnitCount()
    local text = self:GetLabel();
    local widthUnitCount = self:GetTextWidthUnitCount(text);
    if (widthUnitCount > self.FIELD_MAX_WIDTH_UNIT_COUNT) then
        widthUnitCount = self.FIELD_MAX_WIDTH_UNIT_COUNT;
        text = self:GetTextByWidth(text, widthUnitCount);
    end
    self:SetText(text);
    return widthUnitCount + self.FIELD_INPUT_HEIGHT_UNIT_COUNT + TriangleWidthUnitCount, self.FIELD_INPUT_HEIGHT_UNIT_COUNT;
end


function Select:SaveToXmlNode()
    local xmlnode = Select._super.SaveToXmlNode(self);
    return xmlnode;
end

function Select:LoadFromXmlNode(xmlnode)
    Select._super.LoadFromXmlNode(self, xmlnode);
    self:SetLabel(self:GetLabelByValue(self:GetValue()));
end

return Select;